﻿using JshRCSWebApi.Infrastructure;
using JshRCSWebApi.Infrastructure.Domain.DTO.SysService;
using JshRCSWebApi.Infrastructure.Domain.VO.SysService;
using JshRCSWebApi.Service.SysService;
using JshRCSWebApi.SqlSugarDB.Model.jshrcs_initial;
using SqlSugar;
using SqlSugar.Repository;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JshRCSWebApi.ServiceImpl.SysService
{
    public class DepartmentServiceImpl : DepartmentService
    {
        private readonly Repository<dynamic> _repository;

        public DepartmentServiceImpl(Repository<dynamic> repository)
        {
            this._repository = repository;
        }

        /// <summary>
        /// 新增部门
        /// </summary>
        /// <param name="addDTO"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> AddDepartment(DepartmentAddDTO addDTO, int UID)
        {
            var depInfo = new servicedepartment()
            {
                sdParentID = addDTO.sdParentID,
                sdName = addDTO.sdName,
                sdBriefIntroduction = addDTO.sdBriefIntroduction,
                sdPassed = addDTO.sdPassed,
                CreateBy = UID,
                CreateTime = DateTime.Now
            };
            return _repository.Add<servicedepartment>(depInfo) > 0 ? await Task.Run(async () => ApiResult.Success("新增部门成功"))
                                                                    : await Task.Run(async () => ApiResult.Error("新增部门失败"));
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> DeleteDepartment(int ID)
           => _repository.Context.Deleteable<servicedepartment>().In(ID).ExecuteCommand() > 0 ?
                              await Task.Run(async () => ApiResult.Success("删除部门成功")) : await Task.Run(async () => ApiResult.Error("删除部门失败"));

        /// <summary>
        /// 获取部门列表(分页)
        /// </summary>
        /// <param name="searchDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> GetDepartmentList(DepartmentSearchDTO searchDTO)
        {
            int total = 0;
            var subDepartments = _repository.Context.Queryable<servicedepartment>()
                                                    .OrderBy(sd => sd.sdSort)
                                                    .ToPageList(searchDTO.pageNo, searchDTO.pageSize, ref total)
                                                    .Select(d => new DepartmentSearchVO
                                                    {
                                                        ID = d.ID,
                                                        sdParentID = d.sdParentID,
                                                        sdParentName = d.sdParentID == 0 ? "#" : _repository.Select<servicedepartment>().Where(s => s.ID == d.sdParentID).First().sdName,
                                                        sdName = d.sdName,
                                                        sdDepartmentManagerIDs = d.sdDepartmentManagerIDs,
                                                        sdDepartmentManagerNames = d.sdDepartmentManagerNames,
                                                        sdBriefIntroduction = d.sdBriefIntroduction,
                                                        sdPassed = d.sdPassed,
                                                        sdSort = d.sdSort,
                                                        slSUName = _repository.Select<serviceuser>(su => su.ID == d.ModifyBy)?.suName??string.Empty,
                                                        CreateTime = d.CreateTime
                                                    }).ToList();
            var topLevelDepartments = await GetDepartmentList(subDepartments, 0);
            return await Task.Run(async () => ApiResult.Success("查询成功", new { depList = topLevelDepartments, total = total }));
        }

        /// <summary>
        /// 递归查询
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public async Task<List<DepartmentSearchVO>> GetDepartmentList(List<DepartmentSearchVO> subDepartments, long parentId)
        {
            var newlist = subDepartments.Where(D => D.sdParentID == parentId).ToList();
            if (newlist.Count > 0)
            {
                newlist.ForEach(async d =>
                {
                    d.children = await GetDepartmentList(subDepartments, d.ID); // 递归查询子部门
                });
                return await Task.Run(async () => newlist);
            }
            return null;
        }

        /// <summary>
        /// 查询部门列表（分页 + 非树形）
        /// </summary>
        /// <param name="searchDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> GetDepartmentListByMutiCondtion(DepartmentSearchByConditionDTO searchDTO)
        {
            int total = 0;
            var depList = _repository.Context.Queryable<servicedepartment>()
                                            .WhereIF(!string.IsNullOrEmpty(searchDTO.sdName), d => d.sdName.Contains(searchDTO.sdName))
                                            .WhereIF(searchDTO.stratTime != default(DateTime) && searchDTO.endTime != default(DateTime), d => d.CreateTime <= searchDTO.endTime && d.CreateTime >= searchDTO.stratTime)
                                            .ToPageList(searchDTO.pageNo, searchDTO.pageSize, ref total)
                                            .Select(d => new
                                            {
                                                ID = d.ID,
                                                sdParentID = d.sdParentID,
                                                sdParentName = _repository.Select<servicedepartment>().Where(s => s.ID == (d.sdParentID == 0 ? 1 : d.sdParentID)).First().sdName,
                                                sdName = d.sdName,
                                                sdDepartmentManagerIDs = d.sdDepartmentManagerIDs,
                                                sdDepartmentManagerNames = d.sdDepartmentManagerNames,
                                                sdBriefIntroduction = d.sdBriefIntroduction,
                                                sdPassed = d.sdPassed,
                                                CreateTime = d.CreateTime
                                            }).ToList();
            return await Task.Run(async () => ApiResult.Success("查询成功", new { depList, total }));
        }

        /// <summary>
        /// 获取部门ID与Name集合
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> GetDepartmentNameAndIDList()
        {
            var depInfoList = _repository.SelectList<servicedepartment>()
                                       .Select(d => new {ID = d.ID,sdName = d.sdName})
                                        .ToList();
            return await Task.Run(() => ApiResult.Success("查询成功", depInfoList));
                                          
        }

        /// <summary>
        /// 获取部门管理者
        /// </summary>
        /// <param name="sdid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> SelectDepartmentManager(int sdid)
        {
            var depManagerList =  _repository.Context.Queryable<servicedepartment>()
                                        .LeftJoin<serviceuser>((sd,su) => $",{sd.sdDepartmentManagerIDs},".Contains($",{su.ID},"))
                                         .Where((sd, su) => sd.ID == sdid && su.ID != 0)
                                         .Select((sd,su) => new DepartmentManagerVO()
                                         {
                                             ID = su.ID,
                                             suName = su.suName
                                         }).ToList();
            return await Task.Run(async () => ApiResult.Success("查询成功", new { userList = depManagerList, total = depManagerList.Count() }));
        }

        /// <summary>
        /// 获取部门用户
        /// </summary>
        /// <param name="sdid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> SelectDepartmentUser(int sdid)
        {
            var userInfo =  _repository.Context.Queryable<servicedepartment>()
                                    .LeftJoin<serviceuser>((sd, su) => sd.ID == su.suSDID)
                                    .Where((sd, su) => !$",{sd.sdDepartmentManagerIDs},".Contains($",{su.ID},"))
                                    .Where((sd, su) => sd.ID == sdid && su.ID != 0)
                                    .Select((sd,su) => new DepartmentManagerVO { ID = su.ID, suName = su.suName })
                                    .ToList();
            return await Task.Run(async () => ApiResult.Success("查询成功", new { userList = userInfo, total = userInfo.Count() }));
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="updateDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> UpdateDepartment(DepartmentUpdateDTO updateDTO, int UID)
        {
             var count =  _repository.UpdateColumns(new servicedepartment()
                            {
                                sdParentID = updateDTO.sdParentID,
                                sdName = updateDTO.sdName,
                                sdPassed = updateDTO.sdPassed,
                                sdBriefIntroduction = updateDTO.sdBriefIntroduction,
                                sdDepartmentManagerNames = updateDTO.sdDepartmentManagerNames,
                                sdDepartmentManagerIDs = updateDTO.sdDepartmentManagerIDs,
                                ModifyBy = UID,
                                ModifyTime = DateTime.Now
                            }, d => d.ID == updateDTO.ID,
                            new string[] { "sdParentID", "sdName", "sdPassed", "sdBriefIntroduction", 
                                "sdDepartmentManagerNames", "sdDepartmentManagerIDs","ModifyBy","ModifyTime" });
                return count > 0 ? await Task.Run(async () => ApiResult.Success("修改成功")) :
                                   await Task.Run(async () => ApiResult.Error("修改失败"));
        }
    }
}
